/**
 * @description 通用工具方法
 */
"use strict";

const cp = require("child_process");

function isObject(o) {
  return Object.prototype.toString.call(o) === "[object Object]";
}

/**
 * 下载模板loding
 * @param {string} msg
 * @param {string} spinnerString
 */

function spinnerStart(msg, spinnerString = "|/-\\") {
  var Spinner = require("cli-spinner").Spinner;
  var spinner = new Spinner(msg + "processing.. %s");
  spinner.setSpinnerString(spinnerString);
  spinner.start();
  return spinner;
}

/**
 * 结束当前进程
 */
function sleep() {
  return new Promise((resolve) => setTimeout(resolve, 1000));
}

/**
 * 兼容系统
 * @param {string} command 命令
 * @param {string} args 参数
 * @param {object} options 执行方式
 */
function exec(command, args, options) {
  const win32 = process.platform === "win32";
  const cmd = win32 ? "cmd" : command;
  const cmdArgs = win32 ? ["/c"].concat(command, args) : args;
  return cp.spawn(cmd, cmdArgs, options || {});
}

/**
 * 监听安装进程是否成功
 * @param {string} command 命令
 * @param {string} args 参数
 * @param {object} options 执行方式
 */
function execAsync(command, args, options) {
  return new Promise((resolve, reject) => {
    const p = exec(command, args, options);
    p.on("error", (e) => {
      reject(e);
    });
    //进程退出，成功安装
    p.on("exit", (e) => {
      resolve(e);
    });
  });
}

/**
 * 检查命令白名单
 * @param {Array} commandArr 命令数组
 * @param {string} cmd 单个命令
 */
function checkCommand(commandArr, cmd) {
  if (commandArr.includes(cmd)) {
    return cmd;
  }
}

/**
 * 项目命名规则是否符合
 *  1.首字符必须为英文字符
    2.尾字符必须为英文或数字，不能为字符
    3.字符仅允许"-_"
 * @param {string} nameString 项目名称
 */
function testStringName(nameString) {
  if (
    !/^(@[a-zA-Z0-9-_]+\/)?[a-zA-Z]+([-][a-zA-Z][a-zA-Z0-9]*|[_][a-zA-Z][a-zA-Z0-9]*|[a-zA-Z0-9])*$/.test(
      nameString
    )
  ){
    return false
  }
  return true;
}

module.exports = {
  isObject,
  spinnerStart,
  sleep,
  exec,
  execAsync,
  checkCommand,
  testStringName
};
